package com.richapp.launcher.ui.fragments.home;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.richapp.launcher.R;
import com.richapp.launcher.receiver.LauncherMessageReceiver;
import com.richapp.launcher.ui.fragments.BaseFragment;
import com.richapp.launcher.ui.view.MarqueeText;
import com.richapp.launcher.utils.Tools;

public class Title_Fragment extends BaseFragment {
	MarqueeText notifyText = null;
	TextView time = null;
	ImageView wifi_state = null;
	IntentFilter intentFilter = null;
	TextView notifyTag = null;
	TextView userInfo = null;
	ImageView userLogo = null;

	public static List<String> notifyList = new ArrayList<String>();
	private static final String TAG = Title_Fragment.class.getName();

	public static final String ACTION_USER_MESSAGE_RECEIVE = "com.richapp.launcher.user.message";

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		intentFilter = new IntentFilter();
		intentFilter.addAction(Intent.ACTION_TIME_TICK);
		intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
		intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
		intentFilter.addAction(LauncherMessageReceiver.ACTION_USER_UPDATE_INFO);
		intentFilter.addAction(LauncherMessageReceiver.ACTION_SENSOR_STATUS);
		intentFilter.addAction(LauncherMessageReceiver.ACTION_SENSOR_ALARM);
		intentFilter.addAction(ACTION_USER_MESSAGE_RECEIVE);
		getActivity().registerReceiver(broadcastReceiver, intentFilter);

		View smartHomeTitle = inflater.inflate(R.layout.smarthometitle,container, false);
		init(smartHomeTitle);
		time.setText(getTime());
		if (CheckNetWork().equals(ETHERNET)) {
			wifi_state.setImageResource(R.drawable.ethernet);
		}else if (CheckNetWork().equals(NETWORKCLOSE)) {
			wifi_state.setVisibility(View.INVISIBLE);
		}

		notifyTag.setText(notifyList.size()+"");
		switchNotifyMessage();

		return smartHomeTitle;
	}

	@Override
	protected void init(View view) {
		notifyText = (MarqueeText) view.findViewById(R.id.notify_text);
		notifyTag = (TextView) view.findViewById(R.id.notifi_tag);
		time = (TextView) view.findViewById(R.id.time);
		wifi_state = (ImageView) view.findViewById(R.id.wifi_state);
		userInfo = (TextView) view.findViewById(R.id.username);
		userLogo = (ImageView) view.findViewById(R.id.userhead);
	}

	@Override
	public void onPause() {
		notifyText.stopScroll();
		super.onPause();
	}

	@Override
	public void onResume() {
		notifyText.startScroll();
		super.onResume();
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onDestroyView() {
		getActivity().unregisterReceiver(broadcastReceiver);
		super.onDestroyView();
	}
    public static final String WIFIOPEN = "WIFIOPEN";
    public static final String ETHERNET = "ETHERNET";
    public static final String NETWORKCLOSE = "NETWORKCLOSE";
	/* 检测网络连接状态 */
	public String CheckNetWork() {
		WifiManager wifiManager = (WifiManager)getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
		if (wifiManager.isWifiEnabled() == false) {
			if (Tools.getAllIps(0).size()>0) {
				return ETHERNET;
			}
			return NETWORKCLOSE;
		}
		return WIFIOPEN;
	}

	BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_TIME_TICK)) {
				time.setText(getTime());
			} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
				wifi_state.setVisibility(View.VISIBLE);
				int level = Math.abs(((WifiManager) getActivity().getApplicationContext().getSystemService(getActivity().WIFI_SERVICE)).getConnectionInfo().getRssi());
				wifi_state.setImageResource(R.drawable.wifi_sel);
				wifi_state.setImageLevel(level);
			}else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
				if (CheckNetWork().equals(ETHERNET)) {
					wifi_state.setImageResource(R.drawable.ethernet);
				}else if (CheckNetWork().equals(NETWORKCLOSE)) {
					wifi_state.setVisibility(View.INVISIBLE);
				}
			}else if(LauncherMessageReceiver.ACTION_USER_UPDATE_INFO.equals(action)){
				String userName = intent.getStringExtra("userName");
				if(userName != null){
					userInfo.setText(userName);
				}

				String userLogoStr = intent.getStringExtra("userLogo");
				if(userLogoStr != null){
					if(!"".equals(userLogoStr.trim())){
						byte[] buffer = Base64.decode(userLogoStr,Base64.DEFAULT);
						Bitmap bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
						userLogo.setImageBitmap(bitmap);
					}
				}
			}else if(action.equals(LauncherMessageReceiver.ACTION_SENSOR_STATUS)){
				String msg = intent.getStringExtra("deviceName")+":"+intent.getStringExtra("deviceStatus");
				addNotifyMessage(msg);
				notifyTag.setText(notifyList.size()+"");
			}else if(action.equals(LauncherMessageReceiver.ACTION_SENSOR_ALARM)){
				String msg = intent.getStringExtra("deviceName");
				addNotifyMessage(msg);
				notifyTag.setText(notifyList.size()+"");
			}else if(action.equals(ACTION_USER_MESSAGE_RECEIVE)){
				String msg = intent.getStringExtra("message");
				addNotifyMessage(msg);
				notifyTag.setText(notifyList.size()+"");
			}
		}
	};

	public String getTime() {
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
		Date date = new Date();
		return sdf.format(date);
	}

	private void addNotifyMessage(String message){
		if((notifyList.size()+1) > 20){
			notifyList.remove(0);
		}
		notifyList.add(message);
	}

	private void switchNotifyMessage(){
		final Handler handler = new Handler(){
			int i = 0;
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 0x01){
					if(notifyList.size() < 1){
						notifyText.setText("-_-欢迎使用智能家居服务-_-");
					}else{
						notifyText.setText( notifyList.get(i % notifyList.size()));
					}
					i++;
					if(i > 1000){
						i = 0;
					}
				}
			}
		};

		new Timer().schedule(new TimerTask() {
			@Override
			public void run() {
				handler.sendEmptyMessage(0x01);
			}
		}, 1000, 8*1000);
	}

}
